<?php
/**
 * Created by PhpStorm.
 * User: ljc
 * Date: 2018/8/9
 * Time: 23:44
 */

namespace App\Services;


use Houdunwang\WeChat\WeChat;
use Modules\Weixin\Entities\WxConfig;
use Modules\Weixin\Entities\WxKeywords;
use Modules\Weixin\Entities\WxRule;

class WechatService
{
	public function __construct()
	{
		//获取wechat.php配置文件的内容
		$config = include base_path('config') . '/wxconfig.php';
		//获取数据库中的微信配置数据
		$wxconfig =WxConfig::pluck('value','name')->toArray();
		//将2个数组合并
		$config = array_merge($config,$wxconfig);
		WeChat::config($config)->valid();
	}

	/**
	 * 加载关键词模板
	 */
	public function ruleView($rule_id=0){
		$rule=WxRule::findOrNew($rule_id);
		return view('weixin::ruleView.rule',compact('rule'));
	}

	public function __call($name, $arguments)
	{
		return call_user_func_array([WeChat::class,$name],$arguments);
	}
	public function saveRule($rule_id=0){
		$post=json_decode (request ()->input('rule'),true);
		$rule=WxRule::findOrNew($rule_id);
		$rule->name=$post['name'];
		$rule->module=\HDModule::currentModule();
		$rule->save();
		WxKeywords::where('rule_id',$rule_id)->delete();
		foreach($post['keywords'] as $v){
			WxKeywords::create([
				'key'=>$v['key'],
				'rule_id'=>$rule['id']
			]);
		}
		return $rule['id'];
	}
}